package bookshop.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bookshop.service.LoginService;

public class BookManageFilter implements Filter {

	public BookManageFilter() {

	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		if ((response instanceof HttpServletResponse) && (request instanceof HttpServletRequest)) {
			HttpServletRequest res = (HttpServletRequest) request;
			HttpServletResponse resp = (HttpServletResponse) response;
			String url = res.getRequestURL().toString();
			String status = res.getParameter("status");
			String name = res.getParameter("name");
			LoginService loginService = new LoginService();
			// 验证cookie中存的ticket是否有效,有效直接放行
			if (loginService.checkCookie(res, resp)) {
				chain.doFilter(request, response);
				return;
			}
			 //cas-server返回的status字段是否有并且是否等于successful,等于则设置自己的校验的cookie和session
			if ("successful".equals(status)) {				
				res.getSession().setAttribute("username", name);
				loginService.setCookieSession(res, resp, name);
				String uri = url.split("\\?")[0];
				if (uri != null) {
					resp.sendRedirect(uri);
				}
				return;
			}
			//检验参数中是否有sso_token决定重定向的路径
			String sso_token = request.getParameter("sso_token");
			if (sso_token == null) {
				resp.sendRedirect("http://localhost:8080/cas_server/checkCookiesServlet?appUrl=" + url);
				return;
			} else {
				resp.sendRedirect(
						"http://localhost:8080/cas_server/checkTokenServlet?appUrl=" + url + "&sso_token=" + sso_token);
				return;
			}

		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
